<?php
/*Convert Functions For XML Fields to DB Fields*/
function GetBugDBFieldsByXMLFields($XMLFields,$_LANG)
{
	$DBFields = array();
	foreach($XMLFields as $Item)
	{
		array_push($DBFields,$_LANG['BugImport'][$Item]);
	}
	return $DBFields;
}

/*Get MustImport and Optional Import Fields*/
function GetBugMustImportFields($_LANG)
{	
	$MustImportFields = $_LANG['BugMustImportFields'];
	return $MustImportFields;
}
function GetBugOptionalImportFields($_LANG)
{
	$OptionalImportFields = $_LANG['BugOptionalImportFields'];
	return $OptionalImportFields;	
}

/*Filter out the ImportFields wiht MustImportFields and OptionalImportFields*/
function FilterBugImportFields($ImportFields,&$FilteredImportFields,$MustImportFields,$OptionalImportFields)
{
	$BugIDColumnNumber = 0;  // 初始化BugID对应的列序号			
  
  //Filter the ImportFields with the MustImportFields and OptionalImportFields,
  if($ImportFields)
  {
  	//$Key是列序号,Value是列的名称
  	foreach($ImportFields as $Key => $Value)
   	{
   		//获取BugID Field所在的列号 
    	if(trim($Value)=="BugID")
      {
      		$BugIDColumnNumber = $Key; //Bug ID的Key
      }
      
      if(in_array(trim($Value),$MustImportFields) || in_array(trim($Value),$OptionalImportFields))
      {
          $FilteredImportFields[$Key] = $Value;
      } 	
    }
    $FilteredImportFields[] = 'ProjectID';
    $FilteredImportFields[] = 'ModuleID';
	}
	return 	$BugIDColumnNumber;
}

/*Valiate the ProjectName,ModulePath and BugTitle*/
function GetBugValidateColumns($ImportItem,$ImportFields)
{
    //判断Bug的ProjectID、ModuleID和BugTitle是否合法，并返回
    global $_LANG;
		
    $ProjectModules = array();
 		
 		//To Find the ProjectID with the ProjectName
    $ProjectName = trim($ImportItem[array_search('ProjectName', $ImportFields)]);
    $ProjectInfo = dbGetRow('TestProject', 'ProjectID', "ProjectName='{$ProjectName}'");
    if($ProjectInfo)
    {
       $ProjectModules['ProjectID'] = $ProjectInfo['ProjectID'];
    }
    else
    {
    		//If we can not find the ProjectID, set it to 1
        $ProjectModules['ProjectID'] = 1;
        //$ProjectModules['error'] = $_LANG['ImportMsg']['project_not_existed'];
        //return $ProjectModules;
    }
		
    if(!in_array($ProjectModules['ProjectID'],array_keys(baseGetUserACL($_SESSION['TestUserName']))) )
    {
        $ProjectModules['error'] = $_LANG['ImportMsg']['project_no_permission'];
        return $ProjectModules;
    }

		//To Find the ModuleID with ModulePath
    $ProjectModules['ModuleID']=-1; //初始化为-1
    $ModuleListArray = testGetProjectModuleList($ProjectModules['ProjectID'],'Bug');
    foreach($ModuleListArray as $Item)
    {
         if(trim($ImportItem[array_search('ModulePath', $ImportFields)]) == trim($Item['NamePath']))
         {
             $ProjectModules['ModuleID'] = $Item['ModuleID'];
             break;
         }
    }
    if($ProjectModules['ModuleID']==-1)//模块路径不存在
    {
    		//If the ModulePath can not be found, set it to root path
    		$ProjectModules['ModuleID'] = 0;
        //$ProjectModules['error'] = $_LANG['ImportMsg']['module_not_existed'];
        //return $ProjectModules;
    }

		//Validate the Title	       
    $ProjectModules['BugTitle'] = trim($ImportItem[array_search('BugTitle', $ImportFields)]);
    if(!$ProjectModules['BugTitle'])//Bug标题为空
    {
        $ProjectModules['error'] = $_LANG['ImportMsg']['title_empty'];
        return $ProjectModules;
    }

    return $ProjectModules;
}

/* Get BugInfo with ID:BugID*/
function GetBugIDInfo($BugID)
{
	$BugInfo = dbGetRow('BugInfo', 'BugID', "BugID='{$BugID}'");
	return $BugInfo;
}

/*Copy the SrcBugInfo to $DstBugInfo*/
function CopyBugInfo($SrcBugInfo,&$DstBugInfo,$_LANG)
{
	foreach($_LANG['BugFields'] as $Key => $Value)
	{
			$DstBugInfo[$Key]=$SrcBugInfo[$Key];
	}
}

/* Check Import Field's Value*/
function CheckBugImportFieldValue($FieldName,$Value)
{
		$Result = false;
		switch($FieldName)
		{
      case 'BugStatus':
      	if(in_array($Value,$_LANG['BugStatuses']))
        {
        		$Result = true;
        }
        break;
      default:
        $Result = true;
    }
    return $Result;      
}

/* Update BugInfo of Bug with ID:BigID*/
function UpdateBugInfo($BugID,$ImportFields,$ImportItem,$ValidateColumns,$_LANG)
{
	//Get RawBugInfo
	$RawBugInfo = dbGetRow('BugInfo', '', "BugID='{$BugID}'");
	                        
	//Check And Set The Import Field Value 
	$EditBugInfo = array();
  foreach($ImportFields as $Key => $Value)
  {
    $FieldName = trim($Value);
    if($FieldName == 'ProjectID')
    {
    	$FieldValue = $ValidateColumns['ProjectID'];	
    }
    elseif($Value == 'ModuleID')
    {
    	$FieldValue =  $ValidateColumns['ModuleID'];
    }
    else
    {
    	$FieldValue = trim($ImportItem[$Key]);
    }
    
    $EditBugInfo[$FieldName] = $FieldValue;
  }//end foreach
  
  $EditBugInfo['TestUserName'] = sysAddSlash($_SESSION['TestUserName']);
  $EditBugInfo['LastActionID'] = testGetLastActionID('Bug',$RawBugInfo['BugID']);
  //Rainy_Debug($EditBugInfo,__FUNCTION__,__LINE__,__FILE__);  
   
  //Update the BugInfo                        
  $ActionMsg = testEditBug($EditBugInfo);
  unset($EditBugInfo);
  
  if(!empty($ActionMsg['FailedMsg']))
  {
  	Rainy_Debug($ActionMsg['FailedMsg'],__FUNCTION__,__LINE__,__FILE__);
  	return false;
  }
  return true;
}

/*Add a new Bug In DB*/
function AddNewBug($ImportFields,$ImportItem,$ValidateColumns,$_LANG)
{
	$InsertFields = array();
  foreach($ImportFields as $Key => $Value)
  {
  	$ImportItem[$Key]=trim($ImportItem[$Key]);
    $Value = trim($Value);
    if($Value!='BugID')
    {
    	$InsertFields[$Key] = $Value;
    	//Check Bug ImportFieldValue, 
    	if(CheckBugImportFieldValue($Value,$ImportItem[$Key]) === true)
    	{
    		$InsertFields[$Key] = $Value;
    		if($Value == 'ProjectID')
    		{
    			$ImportItem[$Key] = $ValidateColumns['ProjectID'];	
    		}
    		elseif($Value == 'ModuleID')
    		{
    			$ImportItem[$Key] =  $ValidateColumns['ModuleID'];
    		}
    	}
    }//end if
	}//end foreach

	//Set the InsertKeyValue
	$InsertKeyValue = array();
  foreach($InsertFields as $Key => $Value)
  {
  	$InsertKeyValue[$Value] = addslashes($ImportItem[$Key]);
  }
  $InsertKeyValue['TestUserName'] = sysAddSlash($_SESSION['TestUserName']);
  
  $ActionMsg = testOpenBug($InsertKeyValue);

  unset($InsertKeyValue);
  unset($InsertFields);
  
  if(!empty($ActionMsg['FailedMsg']))
  {
  	Rainy_Debug($ActionMsg['FailedMsg'],__FUNCTION__,__LINE__,__FILE__);
  	return false;
  }
  return true;
}

/*Import the BugList to the DB*/
function ImportBugs($ImportItemList,$ImportFields,$ImportFieldArray,$BugIDColumn,$_LANG)
{
        $ImportTotalItem = 0;
        $ImportSuccessItem = 0;
        $ImportFailItem = 0;
        $ImportAddItem = 0;
        $ImportUpdateItem = 0;
        $ErrorMsg = '';
				$FieldCount = count($ImportFields);
				$ItemFieldCount = 0;
				
         foreach($ImportItemList as $ImportItemListKey => $ImportItemListValue)
         {     
              $ImportTotalItem = $ImportTotalItem + 1;
              
              //Confirm if ImportItem is NULL
              if(!$ImportItemListValue)
              {
             			$ErrorMsg .= 'Import row '.$ImportTotalItem.' failed:[ImportItem is empty or with empty field(s)]\n';		
              		Rainy_Debug("Import row [{$ImportTotalItem}] Failed: ImportItemListValue is NULL",__FUNCTION__,__LINE__,__FILE__);
              		continue;
              }
              
              //Check ImportItem have the same fields with ImportFields
              $BugID = $ImportItemListValue[$BugIDColumn];
              $ItemFieldCount = count($ImportItemListValue);
              if($FieldCount != $ItemFieldCount)
              {
             			$ErrorMsg .= 'Import row '.$ImportTotalItem.' BugID['.$BugID.'] failed:[ImportItem have empty field(s)]\n';
              		Rainy_Debug("Import row [{$ImportTotalItem}] BugID [{$BugID}] Failed: ItemFieldCount ='{$ItemFieldCount}' [$FieldCount]",__FUNCTION__,__LINE__,__FILE__);				
              		//Rainy_Debug($ImportItemListValue,__FUNCTION__,__LINE__,__FILE__);
              		continue;
              }
              
              //Get ProjectID and ModuleID and Check BugTitle
              $ValidateColumns = GetBugValidateColumns($ImportItemListValue,$ImportFieldArray); //判断字段的合法位
              if(isset($ValidateColumns['error']))
              {
                 	$ErrorMsg .= 'Import row '.$ImportTotalItem.' BugID['.$BugID.'] failed:['.$ValidateColumns['error'].']\n';
              		Rainy_Debug("Import row [{$ImportTotalItem}] BugID [{$BugID}] Failed: {$ValidateColumns[error]}",__FUNCTION__,__LINE__,__FILE__);	
              		continue;
              }
              
              $BugInfo = GetRawBugInfo($BugID);
              if($BugInfo)
              {
              		//BugID存在，则更新Bug相关消息
                  if(UpdateBugInfo($BugID,$ImportFieldArray,$ImportItemListValue,$ValidateColumns,$_LANG) == true)
                  {
                  		$ImportSuccessItem = $ImportSuccessItem + 1;          
                  		$ImportUpdateItem = $ImportUpdateItem + 1;
                  }
                  else
                  {
                  		$ErrorMsg .= 'Import row '.$ImportTotalItem.' BugID['.$BugID.'] failed:[UpdateBugInfo()]\n';
                  		Rainy_Debug("Import row [{$ImportTotalItem}] BugID [{$BugID}] Failed: UpdateBugInfo()",__FUNCTION__,__LINE__,__FILE__);
											//Rainy_Debug($ImportItemListValue,__FUNCTION__,__LINE__,__FILE__);
                  }
              }//end edit bug
		      		else 
		      		{
		      				//BugID不存在，则新增Bug         
		 	        		if(AddNewBug($ImportFieldArray,$ImportItemListValue,$ValidateColumns,$_LANG) == true)
		 	            {
		 	            		$ImportSuccessItem = $ImportSuccessItem + 1;          
 			            		$ImportAddItem = $ImportAddItem + 1; 
		 	            }
		 	            else
		 	            {
		 	            		$ErrorMsg .= 'Import row '.$ImportTotalItem.' BugID['.$BugID.'] failed:[AddNewBug()]\n';
		 	            		Rainy_Debug("Import row [{$ImportTotalItem}] BugID [{$BugID}] Failed: AddNewBug()",__FUNCTION__,__LINE__,__FILE__);
											//Rainy_Debug($ImportItemListValue,__FUNCTION__,__LINE__,__FILE__);
		 	            }
              }
         }
         $ImportFailItem = $ImportTotalItem-$ImportSuccessItem;
         $FinishAlert = str_replace('{param0}',$ImportTotalItem, $_LANG['BugImportFinished']);
         $FinishAlert = str_replace('{param1}',$ImportSuccessItem, $FinishAlert);
         $FinishAlert = str_replace('{param2}',$ImportFailItem, $FinishAlert);
         $FinishAlert = str_replace('{param3}',$ImportAddItem, $FinishAlert);
         $FinishAlert = str_replace('{param4}',$ImportUpdateItem, $FinishAlert);
         if("" != $ErrorMsg)
         {
                $ErrorMsg = '\n'.$ErrorMsg;
         }
         //Rainy_Debug($ErrorMsg,__FUNCTION__,__LINE__,__FILE__);
         sysObFlushJs("alert('{$FinishAlert}{$ErrorMsg}');");
}
?>
